<template>
  <q-dialog v-model="importCard">
    <ImportForm mode="stocks" @update="init"></ImportForm>
  </q-dialog>
  <q-dialog v-model="searchDig"  >
    <StockItemFilterForm ref="stockItemFilterFormRef" @filter="search"></StockItemFilterForm>
  </q-dialog>
  <div class="q-pa-sm report-style">
    <div class="q-gutter-y-md">
      <q-table
        class="card-radius my-table"
        wrap-cells
        flat
        bordered
        :columns="columns"
        :rows="filterRows"
        :pagination="{ rowsPerPage: 15 }"
        row-key="id"
        no-data-label="No stock item found."
        no-results-label="The filter didn't uncover any results"
        @row-dblclick="dblclickFn"
      >
      <template v-slot:top-row="props">
          <ColsFilter :filter="props.cols" ref="colsFilter"></ColsFilter>
      </template>
        <template v-slot:top>
          <div class="row justify-between" style="width: 100%">
            <div class="fal page-header">Stock Item Master</div>
            <div>
              <q-card-actions>
                <q-btn
                  class="default-btn"
                  label="Search"
                  no-caps
                  @click="searchDig = true"
                />
                <q-btn
                  class="yellow-btn"
                  icon-right="file_upload"
                  label="Import"
                  no-caps
                  @click="importCard=true"
                  />
                <q-btn
                  class="blue-btn"
                  icon-right="archive"
                  label="Export default"
                  no-caps
                  @click="genDefaultCSV()"
                />
                <q-btn
                  label="register"
                  class="default-btn q-px-sm"
                  @click="openAddDialog()"
                />
              </q-card-actions>
            </div>
          </div>
        </template>

        <template v-slot:body-cell-actions="props">
          <q-td>
            <div class="text-left">
              <q-btn
                dense
                round
                flat
                class="edit-btn"
                icon="edit"
                @click.stop="openEditDialog(props.row)"
              ></q-btn>
              <q-btn
                dense
                round
                flat
                class="del-btn"
                @click="deleteFn(props.row.id)"
                icon="delete"
              ></q-btn>
            </div>
          </q-td>
        </template>

        <template v-slot:no-data="{ icon, message }">
          <div class="full-width row flex-center text-accent q-gutter-sm">
            <!-- <q-icon size="2em" name="sentiment_dissatisfied" /> -->
            <q-icon size="2em" :name="icon" />
            <span> {{ message }} </span>
          </div>
        </template>
      </q-table>
    </div>
  </div>

  <q-dialog full-height v-model="addDialogVisible">
    <MyBigDialog title="">
      <StockItemForm
        @submit="init"
        :lv="'level 4'"
        :from="'create'"
        @cancel="closeDialog"
      ></StockItemForm>
    </MyBigDialog>
  </q-dialog>

  <q-dialog full-height  v-model="editDialogVisible">
    <MyBigDialog title="">
      <StockItemEditComponent
        @submit="init"
        :stockItem="editedRow"
        @cancel="closeDialog"
      ></StockItemEditComponent>
    </MyBigDialog>
  </q-dialog>

  <q-dialog v-model="deleteDialogVisible">
    <q-card>
      <q-card-section class="bg-red">
        <div class="text-h6 text-white">
          Are you sure to delete stock code {{ editedRow.stock_code }} ?
        </div>
      </q-card-section>

      <q-card-actions align="right">
        <q-btn flat label="No" color="primary" v-close-popup />
        <q-btn
          flat
          label="Yes"
          color="primary"
          @click="removeStockItem"
          v-close-popup
        />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script setup lang="ts">
import { QTableColumn, useQuasar } from 'quasar';
import {HistorySearch, StockItem, stockTtemSearch} from 'src/services/type';
import { ref, computed, reactive } from 'vue';
import StockItemEditComponent from 'src/components/itemMaster/StockItemEditComponent.vue';
import StockItemForm from 'src/components/itemMaster/StockItemForm.vue';
import {
  getStockItemWithChildNumber,
  softDeleteStockItem,
  getEdocCompletionRates,
  getSWVersionCompletion, getStockItemWithChildNumberFilter
} from 'src/services/stockCodeService';
import ColsFilter from 'src/components/table/ColsFilter.vue';
import { softDeletePart } from 'src/services/partsService';
import { exportTable } from 'src/utils/exportCsvUtils';
import ImportForm from 'src/components/import/importForm.vue';
import StockItemFilterForm from 'src/components/reportTable/StockItemFilterForm.vue';
import MyBigDialog from 'src/components/container/MyBigDialog.vue'
import { useVersionStore } from 'src/stores/versionStore';
import {repairOrderHistory} from "@/services/reportService";

const editedRow = ref();
const editDialogVisible = ref(false);
const deleteDialogVisible = ref(false);
const addDialogVisible = ref(false);

const searchDig = ref(false)
const importCard = ref(false)
const model = ref(null);

const $q = useQuasar();

const colsFilter = ref<typeof ColsFilter>();

function openAddDialog() {
  addDialogVisible.value = true;
}

function openEditDialog(row: StockItem) {
  editedRow.value = { ...row };
  console.log(editedRow.value);
  editDialogVisible.value = true;
}

function dblclickFn(evt: any, row: StockItem, index: number) {
  editedRow.value = { ...row };
  editDialogVisible.value = true;
}

/* function openDeleteDialog(row: StockItem) {
  console.log('delte', row);
  editedRow.value = { ...row };

  deleteDialogVisible.value = true;
} */

function deleteFn(id: number) {
  $q.dialog({
    title: 'Confirm',
    message: 'Are you sure to delete this record?',
    cancel: true,
  }).onOk(async () => {
    const res = await softDeleteStockItem(id);
    if (res) {
      $q.notify({
        message: 'Success',
        color: 'positive',
      });
      init();
    }
  });
}

function closeDialog() {
  editDialogVisible.value = false;
  addDialogVisible.value = false;
  addDialogVisible.value = false;
  init();
}

function removeStockItem() {
  console.log('removeStockItem');
  //to do
}

async function genDefaultCSV(){
  const row = rows.value[0]
  console.log(row);
  const cols = []
  for(const col in row){
    if (col=='lv6'||
      col=='id'||
      col=='image'||
      col=='assigned'||
      col=='deleted'||
      col=='purchase_date'||
      col=='io_counter'||
      col=='create'
    ){
      continue
    }
    cols.push( {
    name: col,
    label: col,
    field: col,
    sortable: true,
    search: true,
    align,
  },)
  }
  const output = rows.value.sort(compareNumbers)
  exportTable(cols,output,'Stock Item Master')
}

function compareNumbers(a:StockItem, b:StockItem) {
  return a.id - b.id;
}

const items = ref([]);

const align = 'left';
const columns = ref([
  /*   {
    name: 'id',
    label: '#',
    field: 'id',
    sortable: true,
    align,
    search: false,
    style:'width: 10px',
    headerStyle: 'width: 10px'
  }, */
  {
    name: 'stock_code',
    label: 'Stock Code',
    field: 'stock_code',
    sortable: true,
    search: true,
    align,
  },
  {
    name: 'system',
    label: 'System',
    field: 'system',
    sortable: true,
    search: true,
    align,
  },
  {
    name: 'description',
    label: 'Short Description',
    field: 'description',
    sortable: true,
    search: true,
    align,
  },
  {
    name: 'sw_ver',
    label: 'S/W Version',
    field: 'sw_ver',
    sortable: true,
    search: true,
    align,
  },
  {
    name: 'hw_ver',
    label: 'H/W Version',
    field: 'hw_ver',
    sortable: true,
    search: true,
    align,
  },
  {
    name: 'assigned',
    label: 'No of Childs',
    field: 'assigned',
    sortable: true,
    search: true,
    align,
  },
  {
    name: 'actions',
    label: 'Actions',
    field: 'actions',
    search: false,
    align,
  },
]);

const versionStore =useVersionStore()

const data: StockItem[] = [];

const rows = ref<StockItem[]>(data);

const stockItemFilterFormRef = ref(null)

async function init() {
  // const res = await getStockItemWithChildNumber();
  // const res = await getStockItemWithChildNumberFilter('', '', '');
  //
  // if (res.data) {
  //   rows.value = res.data;
  //   console.log(res.data);
  // }
  // items.value = [];
  // importCard.value = false
  versionStore.init()
}
init();
initEdocCompletion()
initSWVersionCompletion()
async function initEdocCompletion() {
  const res = await getEdocCompletionRates()
  columns.value.splice(6,0,{
    name: 'edoc_completion_rate',
    label: 'Rate of Edoc Completion',
    field: 'edoc_completion_rate',
    sortable: true,
    format:(val, row)=>{
      return res.data[row.id]
    },
    align,
  },)
}
async function initSWVersionCompletion() {
  const res = await getSWVersionCompletion()
  console.log(res.data);
  columns.value.splice(6,0,{
    name: 'sw_ver_completion_rate',
    label: 'Rate of S/W Version Completion',
    field: 'sw_ver_completion_rate',
    sortable: true,
    format:(val, row)=>{
      return res.data[row.id]
    },
    align,
  },)
}


function filterFn(row: StockItem) {
  if (colsFilter.value) {
    return colsFilter.value.filterFn(row);
  }
}

const filterRows = computed(() => {
  return rows.value?.filter(filterFn);
});

function showLoading() {
  $q.loading.show({
    message: 'Doing something. Please wait...',
    boxClass: 'bg-grey-2 text-grey-9',
    spinnerColor: 'primary',
  });
}

async function search(form: { data: stockTtemSearch}){
  stockItemFilterFormRef.value.myDialogSubmitLonding(true);
  // showLoading()
  const res =  await getStockItemWithChildNumberFilter(form.data.stock_code, form.data.system, form.data.description)
  console.log(res);
    if (res.data) {
    rows.value = res.data;
    console.log(res.data);
  }
  searchDig.value = false
  // $q.loading.hide()
  stockItemFilterFormRef.value.myDialogSubmitLonding(false);
}

</script>

<style scoped>
.content {
  display: flex;
  justify-content: space-between;
  background-color: #eef4fa;
  padding-top: 20px;
  padding-right: 10px;
}

.warning {
  color: red;
  font-weight: bold;
  text-align: center;
  width: -webkit-fill-available;
  padding-top: 20px;
}

th,
td {
  text-align: center;
  padding: 10px;
}
</style>
